import router from '@/router'
import {message} from 'ant-design-vue'
import request from 'api/request'
import config from 'public/config/config.js'

export default {
  namespaced:true,
  state:{
    userInfo:null,
    authorityList:[],
    authorityTree:[],
    rules:[]
  },
  mutations:{
    setAuthority(state,data){
      let arr = []
      state.authorityList = JSON.parse(JSON.stringify(data))
      for(let i of data){
        let f = data.filter(e=>e.pid === i.id)
        if(JSON.stringify(f) != "[]"){
          i.children = f
        }
        if(i.pid == 0){
          arr.push(i)
        }
      }
      state.authorityTree = arr
    },
    setRules(state,data){
      state.rules = data
    },
    setUserInfo(state,userInfo){
      sessionStorage.setItem('userInfo',JSON.stringify(userInfo))
      sessionStorage.setItem('token',userInfo.token)
      state.userInfo = userInfo
    },
    outLogin(state){
      sessionStorage.removeItem('userInfo')
      router.push({
        path:'/admin/login'
      })
    }
  },
  actions:{
    getAuthority(context){
      return new Promise((resolve, reject) => {
        request.get("/system/authority/list").then(e=>{
          if(e.status == 200){
            context.commit('setAuthority',e.data)
          }else{
            message.error(e.msg)
          }
          resolve(true) 
        })
      });
    },
    getRules(context){
      return new Promise((resolve, reject) => {
        request.get("/system/rules").then(e=>{
          if(e.status == 200){
            context.commit('setRules',e.data)
          }else{
            message.error(e.msg)
          }
          resolve(true)
        })
      });
    },
    checkLogin(context){
      return new Promise((resolve, reject) => {
        let userInfo = sessionStorage.getItem('userInfo')
        if(userInfo){
          let info = JSON.parse(userInfo)
          context.state.userInfo = info
          resolve([true])
        }else{
          message.error('未登入')
          router.push({
            path:'/admin/login'
          })
          resolve([false])
        }
      });
    },
    async checkAuthority(context,path){ //检查权限
      let [o] = await context.dispatch("checkLogin")
      if(!o){ return {status:400,msg:'未登入'} }
      if(context.state.rules.length == 0){
        await context.dispatch("getRules")
      }
      if(context.state.authorityList.length == 0){
        await context.dispatch("getAuthority")
      }
      let rule_id = context.state.userInfo.rule_id
      let rules = context.state.rules.find(e=>e.id == rule_id).rules.split(",")
      let authorityList = context.state.authorityList.find(e=>e.url == path)
      if(authorityList){
        let authorityId = authorityList.id
        if(rules.find(e=>e == authorityId)){
          return {status:200,msg:'ok'}
        }else{
          return {status:500,msg:'无权限浏览此页面'}
        }
      }else{ //未配置权限返回true
        return {status:200,msg:'ok'}
      }
    }
  }
}